package com.zyc.demo.v.exh;

import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

/**
 * 文件上传超过限制的异常处理器
 */
@RestControllerAdvice
public class MultipartExceptionHandler {

    public static final Logger log = LoggerFactory.getLogger(MultipartExceptionHandler.class);

    private MultipartProperties multipartProperties;

    public MultipartExceptionHandler(MultipartProperties multipartProperties) {
        this.multipartProperties = multipartProperties;
    }


    @ExceptionHandler(value = {MultipartException.class})
    public Object handlerMultipartException(MultipartException e) {

        Throwable cause = e.getCause().getCause();
        if (cause instanceof FileSizeLimitExceededException) {
            if (log.isInfoEnabled()) {
                log.info("上传文件发生异常。单个文件上传超出限制");
            }
            return String.format("文件大小超过限制，单个上传文件大小不能超过%dMB", multipartProperties.getMaxFileSize().toMegabytes());
        } else if (cause instanceof SizeLimitExceededException) {
            if (log.isInfoEnabled()) {
                log.info("上传文件发生异常。上传文件总大小超出限制");
            }
            return String.format("文件大小超过限制，上传文件总大小不能超过%dMB", multipartProperties.getMaxFileSize().toMegabytes());
        }
        if (log.isErrorEnabled()) {
            log.error("上传文件发生异常。", e);
        }
        return "文件上传异常";
    }

    private void printException(Exception e) {
        e.printStackTrace();
    }
}
